# -*- coding: utf-8 -*-
'''
Copyright (C) 2011 olejl77@gmail.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''

import urllib
import re
import xbmc
import xbmcgui
import xbmcaddon
import xbmcplugin
from BeautifulSoup import BeautifulSoup
from Item import Item

__settings__ = xbmcaddon.Addon(id="plugin.video.no.dagbladet")
__language__ = __settings__.getLocalizedString

def createMainMenu(baseUrl, handle):
	'''
	Reads tv categories from dagbladet.no
	When done sends them to Xbmc as the plugin main menu
	'''
	listing = []
	soup = BeautifulSoup(urllib.urlopen('http://www.dagbladet.no/tv/'))
	# TODO '/videoK/' is sufficient to find all categories, but it also catches the category 'Huset'. I'm not able to test
	# 'Huset' so I am expanding the pattern to avoid this channel. 'Huset' doesn't have an category id
	categories = soup.findAll('a', attrs={'href':re.compile('/videoK/http://www.dagbladet.no/tv/c')})
	for category in categories:
		title = category.contents[0]
		cat_id = re.findall(r'\d+$', category['href'])[0]

		# Pagination. Show 12 and 12 items, then add this item for next page
		listing.append(
			Item(
				title=category.contents[0],
				url=baseUrl+"?sub=" + cat_id + "=0")) # The last '0' is the "video index". '0' means start from the first video

	sendToXbmc(handle, listing)

def createSubMenu(baseUrl, handle, cat_id, offset="0"):
	'''
	Reads tv categories from dagbladet.no
	When done sends them to Xbmc as the plugin main menu
	'''
	url = 'http://www.dagbladet.no/api/kommentar/gallery/?op=VideosByCategory&catid=%s&offset=%s' % (cat_id, offset)
	soup = BeautifulSoup(urllib.urlopen(url))
	objs = soup.findAll('obj')

	listing = []
	for obj in objs:
		progid      = obj.mm_id.contents[0]
		title       = obj.caption.contents[0]
		duration    = obj.duration.contents[0]
		viewed      = obj.viewedtimes.contents[0]
		date        = obj.uploadedtime.contents[0]
		rating      = obj.rating.contents[0]
		votes       = obj.votes.contents[0]
		category    = obj.category.contents[0]
		thumb       = 'http://front.xstream.dk/dagbladet/GetThumbnail.php?ClipId=%s' % (progid)
		stream_url  = 'http://front.xstream.dk/dagbladet/xmlgenerator.php?id=%s' % (progid)
		stream_soup = BeautifulSoup(urllib.urlopen(stream_url))
		# Sometimes there is 3 videos, 1 commercial before and after. Making sure we choose the correct one
		stream_url  = stream_soup.find('flv', attrs={'id':re.compile(progid)})['flv8']
		splash      = stream_soup.data['splash']	# TODO For future
		end_splash  = stream_soup.data['end_splash']# TODO For future

		listing.append(
			Item(
				progid=progid,
				title=title,
				duration=duration,
				viewed=viewed,
				date=date,
				rating=rating,
				votes=votes,
				thumb=thumb,
				category=category,
				url=stream_url,
				fanart=splash,
				isPlayable=True))

	# Increase the index with 12 every time since that is the number of videos returned in the XML
	new_offset = int(offset) + 12

	# Next page (12 new videos)
	listing.append(
		Item(
			title=__language__(30000),
			category=cat_id,
			url=baseUrl+"?sub=" + str(cat_id) + "=" + str(new_offset)))

	sendToXbmc(handle, listing)

def sendToXbmc(handle, listing):
	"""
	Sends a listing to XBMC for display as a directory listing
	Plugins always result in a listing
	"""
	# send each item to xbmc
	for item in listing:
		listItem = xbmcgui.ListItem(item.title, thumbnailImage=item.thumb)
		listItem.setInfo(
			type='Video',
			infoLabels={
				'title': item.title, 
				'plot':item.description,
				'duration':item.duration,
				'rating':int(item.rating),
				'playcount':int(item.viewed),
				'date':item.date,
				'votes':item.votes,
				'Property(releasedate)':item.fanart	# TODO not sure about this one ...
			})
		xbmcplugin.addDirectoryItem(handle, item.url, listItem, not item.isPlayable)

	# tell xbmc we have finished creating the directory listing
	xbmcplugin.endOfDirectory(handle)

if ( __name__ == "__main__" ):
	xbmcplugin.setContent(int(sys.argv[1]), "episodes")
	xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
	xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)

	# Probaly not the "correct way...
	# sys.argv[2]: ?sub=<category id>=<offset>
	# Offset is used to paginate the movies within a category
	arg = sys.argv[2].split('=')

	if (arg[0] == "?sub"):
		createSubMenu(sys.argv[0], int(sys.argv[1]), arg[1], arg[2])
	else:
		createMainMenu(sys.argv[0], int(sys.argv[1]))

